package org.jeecg.modules.demo.wuyou.service.impl;

import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.wuyou.entity.WebVisitStats;
import org.jeecg.modules.demo.wuyou.mapper.WebVisitStatsMapper;
import org.jeecg.modules.demo.wuyou.service.IWebVisitStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.concurrent.TimeUnit;

/**
 * @Description: web_visit_stats
 * @Author: jeecg-boot
 * @Date:   2024-10-11
 * @Version: V1.0
 */
@Service
public class WebVisitStatsServiceImpl extends ServiceImpl<WebVisitStatsMapper, WebVisitStats> implements IWebVisitStatsService {

    @Autowired
    private RedisUtil redisUtil;

    private static final int MAX_VISITS_PER_MINUTE = 10;
    private static final long TIME_WINDOW = 60L;
    public void recordVisit(WebVisitStats clientType) throws Exception {
        String redisKey = "visit:ip:" + clientType.getIp();
        Integer currentVisitCount = (Integer) redisUtil.get(redisKey);


        if (currentVisitCount != null && currentVisitCount >= MAX_VISITS_PER_MINUTE) {
            throw new Exception("Too many requests from this IP");
        }

        // 如果访问次数未超过限制，记录访问并增加访问次数

        this.save(clientType);

        // 增加访问次数并设置一分钟过期时间
        if (currentVisitCount == null) {
            redisUtil.set(redisKey, 1, TIME_WINDOW); // 第一次访问，设置过期时间
        } else {
            redisUtil.incr(redisKey, 1); // 增加访问次数
        }
    }
}
